<template>
  <div class="login-container">

    <!-- 登录表单 -->
    <div class="login-content">
      <div class="login-image">
        <el-image :src="loginImage" style="width: 210px; height: 210px" />
      </div>
      <div class="login-box">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
        >

          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-input
                ref="username"
                v-model="loginForm.username"
                name="username"
                size="large"

                placeholder="请输入用户名"
                class="h-[48px]"
              >
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />

              </el-input>
            </div>
          </el-form-item>

          <!-- 密码 -->

            <el-form-item prop="password">
              <div class="input-wrapper">
                <el-input
                  v-model="loginForm.password"
                  placeholder="请输入用户密码"
                  type="password"
                  name="password"

                  @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                >
                  <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />

                </el-input>
              </div>
            </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="captchaCode">
            <div class="input-wrapper">
              <el-input
                v-model="loginForm.captchaCode"
                auto-complete="off"
                size="large"
                class="flex-1"
                 placeholder="请输入验证码"
                @keyup.enter="handleLoginSubmit"
              >
                <svg-icon slot="prefix" icon-class="code" class="el-input__icon input-icon" />
                <template #suffix>
                  <el-image
                    @click="getCaptcha"
                    :src="captchaBase64"
                    class="captcha-image"
                  />

                </template>
              </el-input>


            </div>
          </el-form-item>

          <div class="flex-x-between w-full py-1">
            <el-checkbox v-model="loginForm.isRemember">
             记住我
            </el-checkbox>

          </div>
          <div class="login">
            <el-button
              :loading="loading"
              type="primary"
              size="medium"
              @click.prevent="handleLoginSubmit"
            >
              登录
            </el-button>
          </div>




        </el-form>
      </div>
    </div>

  </div></template>

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'
import fileImg from '../../assets/images/login-image.svg'
import { get } from '@/api/requestCommon'
import { fail } from '@/api/common'

export default {
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度小于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        captchaKey:'',
        captchaCode:'',
        isRemember: false
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        captchaCode: [ { required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      loginImage: fileImg,
      captchaBase64:''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },

  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    this.getCaptcha()
  },

  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    getCaptcha(){
      get('captcha').then(res => {
        if (res.code === 200) {
            this.captchaBase64=res.data.captchaValue
            this.loginForm.captchaKey=res.data.captchaKey
        }else{
          fail(res.msg)
        }
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLoginSubmit() {

      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss"  >


</style>


